//On ready load the first column
$(display_tree('../root/',1));


//Click handler
$(".f_entry").live('click', function () {
    
    //Get path
    var path = $(this).attr("path");
    
    //Get column
    var c = parseInt($(this).attr("col"));
    var next = c + 1;
    
    //If folder
    if($(this).attr("type") == 'folder') {
        
        //Ajax diplay tree request function
        display_tree($(this).attr("path"), next);
    
    //If file
    } else {
        
        //Remove all columns after c
        $('#col' + c).nextAll().remove();
        
        //Ajax display file request function
        display_file($(this).attr("path"));
        
        
    }
    //Clear nth-child color and color the right row
    $('#col' + c + ' .f_entry:nth-child(odd)').css({backgroundColor: '#DDD'});
    $('#col' + c + ' .f_entry:nth-child(even)').css({backgroundColor: '#FFF'});
    $(this).css({backgroundColor: '#909090'});
});


//Display the tree, where p is path and c the column
function display_tree(p,c) {
    
    //Clear column content
    $('#col' + c).html('');
    
    //Set up AJAX request
    $.post('php/file_manager.php',
    
        //Variables and Values
        {path: p, col: c},
        function(data) {
            
            //Remove all columns after c
            var rem = c - 1;
            $('#col' + rem).nextAll().remove();
            
            //Create new column and append data
            $("#file_tree").append('<div class="col" id="' + 'col' + c + '" col="'+ c +'"></div>');
            $('#col' + c).append(data);
            
            //Scroll
            var pos = $('#col' + c).offset();
            $('#file_tree').animate({ scrollLeft: pos.left });
    });
}

//Display a file, where p is the path
function display_file(p) {
    
    //Set up AJAX request
    $.post('php/file_viewer.php',
    
        //Variables and Values
        {path: p},
        function(data) {
            
            //Display the file name
            $('#file_name').html(p);
            
            //Insert the text
            editor.getSession().setValue(data);
        });
}